package com.jk.testsql.aop;

import com.alibaba.druid.pool.DruidDataSource;
import com.jk.testsql.constant.DataSourceTypeEnum;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@MapperScan(basePackages = "com.jk.testsql.dao")
public class DataSourceConfig {
    /**
     * 创建主数据源实例
     * @return DataSource
     */
    @Bean(name = "masterDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.master")
    public DataSource masterDataSource() {
        return new DruidDataSource();
    }
    /**
     * 创建从数据源实例
     * @return DataSource
     */
    @Bean(name = "slaveDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.slave")
    public DataSource slaveDataSource() {
        return new DruidDataSource();
    }

    /**
     * 路由数据源
     * @param masterDataSource
     * @param slaveDataSource
     * @return
     */
    @Bean(name = "routingDataSource")
    public DataSource routingDataSource(@Qualifier("masterDataSource") DataSource masterDataSource, @Qualifier("slaveDataSource") DataSource slaveDataSource) {
        Map<Object,Object> targetDataSources = new HashMap<>(2);
        targetDataSources.put(DataSourceTypeEnum.MASTER,masterDataSource);
        targetDataSources.put(DataSourceTypeEnum.SLAVE,slaveDataSource);
        RoutingDataSource routingDataSource=new RoutingDataSource();
        //设置默认数据源为Master
        routingDataSource.setDefaultTargetDataSource(masterDataSource);
        //设置路由表
        routingDataSource.setTargetDataSources(targetDataSources);
        return routingDataSource;
    }
}
